<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>退库管理</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
<style type="text/css">
	.layui-table-click{
	    background-color:#ddf2e9 !important;
	}
</style>
</head>
<body>
	
<div class="x-nav">
	<span class="layui-breadcrumb">
		<a href="">首页</a>
		<a>
		  <cite>退库管理</cite>
		</a>
	</span>
</div>

<!-- 点击行的时候，把行ID存入 -->
<input class="layui-hide" id="cancellingStockId">
<input class="layui-hide" id="cancellingStockNumber">
<input class="layui-hide" id="cancellingType">
<input class="layui-hide" id="warehouseStockId">
<input class="layui-hide" id="customerId">
	
<div id="cancellingStockDiv" hidden>
	<form class="layui-form" id="cancellingStockForm">
		<div class="layui-form-item">
			<input type="hidden" id="id" name="id">
			<input type="hidden" id="userId" name="userId">
			<input type="hidden" id="status" name="status">
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">退库单号</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="cancellingNumber" class="layui-input" type="text" id="cancellingNumber" name="cancellingNumber" style="width:200px">
		      	</div>
			</div>
	      	<div class="layui-inline" style="margin-left: 10px;">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 40px;">创建日期</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="createDate" class="layui-input" type="text" id="createDate" name="createDate" style="width:200px">
		      	</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">退库原因</label>
		      	<div class="layui-input-inline" style="width:200px">
					<select class="layui-input" name="reasonId" id="reasonId" lay-verify="reasonId"  lay-filter="reasonId">
						<option value="">请选择退库原因</option>
						<c:forEach items="${reasonList}" var="reason">
							<option value="${reason.id}">${reason.cancellingReason}</option>
						</c:forEach>
					</select>
				</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 40px;">仓库类型</label>
		      	<div class="layui-input-inline" style="width:200px">
					<select id="source" name="source" class="layui-select" lay-search="" lay-filter="source">
						<option value="">请选择仓库类型</option>
						<option value="1">良品库</option>
						<option value="0">不良品库</option>
					</select>
				</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">仓库名称</label>
		      	<div class="layui-input-inline" style="width:200px">
		        	<select class="layui-input" name="warehouseId" id="warehouseId" lay-verify="warehouseId"  lay-filter="warehouseId">
						<option value="">请选择仓库名称</option>
					</select>
		      	</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 40px;">管理员姓名</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="userName" class="layui-input" type="text" id="userName" name="userName" style="width:200px">
		      	</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">管理员电话</label>
		      	<div class="layui-input-inline">
		        	<input class="layui-input" type="text" id="phone" name="phone" style="width:200px">
		      	</div>
			</div>
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 72px;">仓库地址</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="warehouse_address" class="layui-input" type="text" id="warehouse_address" name="warehouse_address" style="width:200px">
		      	</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">供应商名称</label>
		      	<div class="layui-input-inline" style="width:200px">
		        	<select class="layui-input" name="clientId" id="clientId" lay-verify="clientId"  lay-filter="clientId">
						<option value="">请选择供应商</option>
						<c:forEach items="${customerList}" var="customer">
							<option value="${customer.id}">${customer.customer_name}</option>
						</c:forEach>
					</select>
		      	</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 40px;">供应商负责人</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="contacts_name" class="layui-input" type="text" id="contacts_name" name="contacts_name" style="width:200px">
		      	</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">供应商电话</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="contacts_tel" class="layui-input" type="text" id="contacts_tel" name="contacts_tel" style="width:200px">
		      	</div>
			</div>
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 72px;">供应商地址</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="customer_adress" class="layui-input" type="text" id="customer_adress" name="customer_adress" style="width:200px">
		      	</div>
			</div>
		</div>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="cancellingStockForm" style="margin-left:350px">提交</button>
		&emsp;&emsp;&emsp;&emsp;
		<button class="layui-btn layui-btn-primary">取消</button>
	</form>
</div>

<div id="materielDiv" hidden="hidden">
	<table class="layui-hide" id="materielTable" lay-filter="materielTable"></table>
</div>

<div id="cancellingStockDetailDiv" hidden="hidden">
	<form class="layui-form" id="cancellingStockDetailForm">
		<div class="layui-form-item">
			<input id="detailId" name="id" hidden="hidden">
		</div>
		<div class="layui-form-item">
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 18px;">退库单号</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="cancellingNumber" class="layui-input" type="text" id="detailCancellingNumber" name="cancellingNumber" style="width:200px">
		      	</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">物料名称</label>
		      	<div class="layui-input-inline" style="width:200px">
					<select id="materialId" name="materialId" class="layui-select" lay-verify="materialId" lay-filter="materialId">
						<option value="">请选择物料</option>
					</select>
				</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<div class="layui-form-item">
		    <div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">物料数量</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="materialQuantity" class="layui-input" type="text" id="materialQuantity" name="materialQuantity" style="width:200px">
		      	</div>
			</div>
			<div class="layui-inline">
		    	<label class="layui-form-label" style="margin-left: 50px;">实际退库数量</label>
		      	<div class="layui-input-inline">
		        	<input lay-verify="actualQuantity" class="layui-input" type="text" id="actualQuantity" name="actualQuantity" style="width:200px">
		      	</div>
			</div>
			<div class="layui-inline">
				<font style="color:red; font-size: 24px;">*</font>
		    </div>
		</div>
		<br>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="cancellingStockDetailForm" style="margin-left:350px">提交</button>
		&emsp;&emsp;&emsp;&emsp;
		<button class="layui-btn layui-btn-primary">取消</button>
	</form>
</div>

<!-- 顶部搜索框 -->
<div class="x-body">
     <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select class="layui-input" name="keyword01" id="keyword01" lay-verify="keyword01"  lay-filter="keyword01">
								<option value="">请选择退库原因</option>
								<c:forEach items="${reasonList}" var="reason">
									<option value="${reason.cancellingReason}">${reason.cancellingReason}</option>
								</c:forEach>
							</select>
						</div>
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
	</div>
 	<h2 style="text-align: center;color:#666">退库单</h2>
 	<!-- 退库单头部按钮 -->
   	<xblock>
		<button id="addCancellingStock" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>新增退库单</button>
		<button id="deleteCancellingStocks" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
		<button id="messaging" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-release"></i>发送消息</button>
   	</xblock> 
   	<!-- 退库单列表 -->
 	<table class="layui-hide" id="cancellingStockTable" lay-filter="cancellingStockTable"></table>
 	<!-- 退库单行编辑 -->
 	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
	</script>
	
	<div id='detailDiv' hidden>
		<h2 style="text-align: center;color:#666">退库单详情</h2>
		<!-- 退库单详情头部按钮 -->
	 	<xblock>
			<button id="addDetail" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>选择物料</button>
			<button id="delsDetail" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	 	</xblock>
		<!-- 退库单详情列表 -->
		<table class="layui-hide" id="cancellingStockTableDetail" lay-filter="cancellingStockTableDetail"></table>
 	</div>
	<!-- 退库单详情的编辑 -->
 	<script type="text/html" id="rowToolbarDetail">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
	</script>
	<!-- 库存物料列表 -->
	<div id='inventoryInfoDiv' hidden>
		<xblock>
			<button id="addInventoryInfo" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>添加物料</button>
	 	</xblock>
		<table class="layui-hide" id="inventoryInfoTable" lay-filter=""inventoryInfoTable""></table>
	</div>
	
</div>
	
<script type="text/javascript">
    var cancellingNumber;
    var customerID = 0;
    var warehouseID = 0;
    var source = 0;
	layui.use(['table','layer','upload','form','laydate'], function(){
		table = layui.table;
		var layer = layui.layer;
		var form = layui.form;
		var laydate = layui.laydate;
		var $ = layui.jquery, active = {
			reload:function () {
				var keyword01 = $("#keyword01").val();
				table.reload('cancellingStockTable',{
					method:'get',
					where:{"cancellingReason":keyword01}
				});
			}
		}
		$('.layui-btn').on('click', function(){
			var type = $(this).data('type');
			active[type] ? active[type].call(this) : '';
		});
		
		//退库日期控件
		laydate.render({
        	elem: '#createDate'
        });
		
		//点击行checkbox选中
	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
	        var index = $(this).attr('data-index');
	        var tableBox = $(this).parents('.layui-table-box');
	        //存在固定列
	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
	        } else {
	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
	        }
	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
	        if (checkCell.length>0) {
	            checkCell.click();
	        }
	    });
	
	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
	        e.stopPropagation();
	    });
	    
	  	//监听复选框事件，被选中的行高亮显示
	    table.on('checkbox(cancellingStockTable)', function(obj){
	    	if(obj.checked == true && obj.type == 'all'){
		        //点击全选
		        $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
		    }else if(obj.checked == false && obj.type == 'all'){
		        //点击全不选
		        $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
		    }else if(obj.checked == true && obj.type == 'one'){
		        //点击单行
			    if(obj.checked == true){
			          obj.tr.addClass('layui-table-click');
			    }else{
			          obj.tr.removeClass('layui-table-click');
			    }
		    }else if(obj.checked == false && obj.type == 'one'){
		        //点击全选之后点击单行
		        if(obj.tr.hasClass('layui-table-click')){
		        	obj.tr.removeClass('layui-table-click');
		        }
		    }
	    });
		
	  	//表单的下拉框监听事件
	    form.on('select(source)', function(data){
	        var id = data.value;	//改变后的值
	        selectWare(id);
	        form.render();
	    });
	  	
	    form.on('select(warehouseId)', function(data){
	    	var id = data.value;	//改变后的值
	    	//根据仓库ID获取管理员信息
	    	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getWarehouseById.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                   	//赋值
                   	$("#warehouse_address").val(datas[0].warehouse_address);
                   	$("#userName").val(datas[0].userName);
                   	$("#phone").val(datas[0].phone);
                }
          	});
	    	//根据仓库ID获取物料信息
	    	/* $.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getMaterielByWarehouseId.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                	//设置下拉列表中的值的属性
                    for ( var i = 0; i < datas.length; i++) {
                    	//增加下拉列表。
                      	$("#materielId").append("<option value='"+datas[i].id+"'>"+datas[i].materiel_name+"</option>");
        			}
                }
          	}); */
	    });
	  	
	  	//根据客户ID获取联系人信息
	    form.on('select(clientId)', function(data){
	    	var id = data.value;	//改变后的值
	    	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getClientById.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                   	//赋值
                   	$("#contacts_name").val(datas[0].contacts_name);
                   	$("#contacts_tel").val(datas[0].contacts_tel);
                   	$("#customer_adress").val(datas[0].customer_adress);
                }
          	});
	    });
	  	
	  	//根据物料ID获取库存数量
	   /*  form.on('select(materielId)', function(data){
	    	var id = data.value;	//改变后的值
	    	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockDetailManager/getQuantityByMid.do",
                data:{"id":id},
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                   	//赋值
                   	$("#materialQuantity").val(datas[0].mNum);
                }
          	});
	    }); */
	    
		/* 退库单列表 */
		table.render({
			elem: '#cancellingStockTable'
			,url:'${pageContext.request.contextPath }/cancellingStockManager/listPageCancellingStock.do'
			,title: '退库单列表'
			,id :'cancellingStockTable'
			,limits:[10,20,30]
			,cols: [[
				{type: 'checkbox', fixed: 'left', },
			  	{field:'', title:'序号', type:'numbers', align:'center'},
			  	{field:'cancellingNumber', title:'退库单号', align:'center'},
			  	{field:'createDate', title:'创建时间', align:'center'},
			  	{field:'warehouse_name', title:'仓库名称', align:'center'},
			  	{field:'warehouse_address', title:'仓库地址', align:'center'},
			  	{field:'userName', title:'仓库管理员', align:'center'},
			  	{field:'phone', title:'管理员电话', align:'center'},
			  	{field:'customer_name', title:'供应商名称', align:'center'},
			  	{field:'customer_adress', title:'供应商地址', align:'center'},
			  	{field:'contacts_name', title:'供应商负责人', align:'center'},
			 	{field:'contacts_tel', title:'负责人电话', align:'center'},
			  	{field:'cancellingReason', title:'退库原因', align:'center'},
			  	{field:'cancellingStatus', title:'状态', align:'center'},
			  	{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar',width:100, align: 'center'}
			  	]]
			,page: true
			,height: 480
			,done : function(){
				$("#cancellingStockTableDetail").addClass("layui-hide");
				$("#detailDiv").attr("hidden","hidden");
				$("#barCodeDiv").attr("hidden","hidden");
				$('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    'font-size': 10,
                })
            }
		});
		
		//退库单推送
		$('#messaging').click(function(obj){
			var rowData = table.checkStatus('cancellingStockTable');
			var data = rowData.data;
        	var str = "";
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        	}else if(data.length > 1){
        		toastr.warning("只能选择一条记录！");
        	}else{
        		var roder = data[0].cancellingNumber;
        		$.ajax({
			    	type:'post',
			    	url:'${pageContext.request.contextPath }/cancellingStockManager/sendCancellingStock.do',
			    	data:{"roder":roder},
			    	dataType : "json",
			    	success:function(data){
			    		if(data>0){
			    			toastr.success("发送成功！");
			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
								//关闭模态框
								// 父页面刷新
								window.location.reload();  
							},1000);
			    		}else{
			    			toastr.error("发送失败！");
			    		}
			    	}
			    })
        	}
		});
		
		//新增退货单
		$('#addCancellingStock').click(function(){
			layer.open({
				type: 1 		//Page层类型
				,area: ['850px', '500px'] //宽  高
				,title: '新增'
				,shade: 0.1 	//遮罩透明度
				,shadeClose: true //点击遮罩关闭
				,maxmin: true //允许全屏最小化
				,anim: 1 		//0-6的动画形式，-1不开启
				,content: $('#cancellingStockDiv')
				,success: function () {
					document.getElementById("cancellingStockForm").reset();
					$("#id").val("")
                 	$("#cancellingNumber").val(curentTimeNumber());	//调用方法，自动生成退货单号
                  	$("#createDate").val(curentTime());	//调用方法，获取当前时间
				}
				,end: function () {
					var formDiv = document.getElementById('cancellingStockForm');
					formDiv.style.display = '';
					layer.close();
				}
			});
		});
		
		//批量删除退货单
		$('#deleteCancellingStocks').click(function(obj){
        	var rowData = table.checkStatus('cancellingStockTable');
			var data = rowData.data;
        	var str = "";
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        	}else{
        		for(var i=0;i<data.length;i++){
            		str += data[i].id;
            		if(i != data.length-1){
            			str += ",";
            		}
            	}
        		layer.confirm('确定删除吗？', function(index){
    				$.ajax({
    			    	type:'post',
    			    	url:'${pageContext.request.contextPath }/cancellingStockManager/deleteCancellingStock.do',
    			    	data:{"ids":str},
    			    	dataType : "json",
    			    	success:function(data){
    			    		if(data>0){
    			    			toastr.success("删除成功！");
    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
    								//关闭模态框
    								// 父页面刷新
    								window.location.reload();  
    							},1000);
    			    		}else{
    			    			toastr.error("删除失败！");
    			    		}
    			    	}
    			    })
    		    layer.close(index);
    			});
        	}
		});
		
		//退库单的编辑
		table.on('tool(cancellingStockTable)', function(obj){
			var data = obj.data;
			var checkStatus = table.checkStatus(obj.data.id);
			$('#cancellingStockId').val(obj.data.id);
			if(obj.event === 'edit'){
				layer.open({
					type: 1 		//Page层类型
					,area: ['850px', '600px'] //宽  高
					,title: '编辑'
					,shade: 0.1 	//遮罩透明度
					,maxmin: true //允许全屏最小化
					,anim: 1 		//0-6的动画形式，-1不开启
					,content: $('#cancellingStockDiv')
					,success: function () {
						//回显表单数据
						for(var i=0;i<Object.entries(data).length;i++) {
							var id = '#' + Object.entries(data)[i][0];
							var text = Object.entries(data)[i][1];
							$(id).val(text);
						}
						var id = data.source;	//改变后的值
				        selectWare(id);
				        $("#warehouseId").val(data.warehouseId)
						form.render();
					}	
					,end: function () {
						var formDiv = document.getElementById('cancellingStockForm');
					  	formDiv.style.display = '';
					  	layer.closeAll();
				  	}
				});
			}
		});
		
		/**
		 * 退库单的提交(新增/编辑)
		 */
		form.on('submit(cancellingStockForm)', function (data) {
			var title = "新增";
			var url = '${pageContext.request.contextPath}/cancellingStockManager/saveCancellingStock.do';
			var id = $.trim($("#cancellingStockId").val());
			if(id != "" && id != null && id != 'undefined'){
				url = '${pageContext.request.contextPath}/cancellingStockManager/updateCancellingStock.do';
				title = "修改";
			}
			$.ajax({
				url : url,
				data: $("#cancellingStockForm").serialize(),
				cache : false,
				type : "post",
			}).done(
				function(res) {
					if (res > 0) {
						toastr.success(title + '成功！');
					}else{
						toastr.error(title + '失败！');
					}
					setTimeout(function(){
						location.reload();
					},1000);
				}
			).fail(
				function(res) {
					toastr.error(title + '失败！');
					setTimeout(function(){
						location.reload();
					},1000);
				}
			)
			return false;
		});
		
		//监听行单击事件(退库单详情列表)
		table.on('row(cancellingStockTable)', function(obj){
			$("#cancellingStockTableDetail").removeClass("layui-hide");
			$('#detailDiv').removeAttr("hidden");
			$('#cancellingStockNumber').val(obj.data.cancellingNumber);
			$('#cancellingType').val(obj.data.source);
			$('#warehouseStockId').val(obj.data.warehouseId);
			$('#customerId').val(obj.data.clientId);
			customerID = obj.data.clientId;
			warehouseID = obj.data.warehouseId;
			cancellingNumber = obj.data.cancellingNumber;
			source = obj.data.source;
			table.render({
				elem: '#cancellingStockTableDetail'
				,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageCancellingStockDetail.do?cancellingNumber='+cancellingNumber
				,title: '退库单详情列表'
				,limits:[10,20,30]
				,cols: [[
				  	{type: 'checkbox', fixed: 'left', },
				  	{field:'cancellingNumber', title:'退库单号', hide:true},
				  	{field:'materiel_name', title:'物料名称', align:'center'},
				  	{field:'materiel_num', title:'产品码', align:'center'},
				  	{field:'brevity_num', title:'物料简码', align:'center'},
				  	{field:'materiel_size', title:'物料规格', align:'center'},
				  	{field:'materiel_properties', title:'物料型号', align:'center'},
				  	{field:'materialQuantity', title:'物料数量', align:'center', edit: true, event:'quantity', templet: function (row){
						return '<span style="color: blue">'+row.materialQuantity+'</span>';
					}},
				  	{field:'actualQuantity', title:'实际数量', align:'center'},
				  	{field:'detailStatus', title:'状态', align:'center', templet: function (row){
	                    if (row.status == '1') {
	                        return "已退库";
	                    } else {
	                        return "未退库";
	                    }
	                }},
				  	]]
				,page: true
				,height: 480
				,done : function(){
	                $('th').css({
	                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                    'font-size': 10,
	                })
	            }
			});
		}); 
		
		//展示物料（物料列表）
		$('#addDetail').click(function(){
			layer.open({
				type: 1 		//Page层类型
				,area: ['1000px', '500px'] //宽  高
				,title: '物料列表'
				,shade: 0.1 	//遮罩透明度
				,shadeClose: true //点击遮罩关闭
				,maxmin: true //允许全屏最小化
				,anim: 1 		//0-6的动画形式，-1不开启
				,content: $('#inventoryInfoDiv')
				,success: function () {
					layui.use(['table'], function(){
						var table = layui.table;
						table.render({
							elem: '#inventoryInfoTable'
							,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customerID+'&source='+source
							,title: '物料列表'
							,limits:[10,20,30]
							,cols: [[
							  	{type: 'checkbox', fixed: 'left', },
							  	{field:'materiel_name', title:'物料名称', align:'center'},
							  	{field:'materiel_num', title:'产品码', align:'center'},
							  	{field:'brevity_num', title:'简码', align:'center'},
							  	{field:'materiel_size', title:'规格', align:'center'},
							  	{field:'materiel_properties', title:'属性', align:'center'},
							]]
							,page: true
							,done : function(){
				                $('th').css({
				                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
				                    'font-size': 10,
				                })
				            }
						});
			        });
					form.render();
				}
				,end: function () {
					var formDiv = document.getElementById('inventoryInfoDiv');
					formDiv.style.display = '';
					layer.closeAll();
				}
			});
		});
		
		//把物料加入退库单详情
		$('#addInventoryInfo').click(function(obj){
			var cancellingNumber = $('#cancellingStockNumber').val();
			var source = $('#cancellingType').val();
			var warehouseId = $('#warehouseStockId').val();
			var customerId = $('#customerId').val();
			var rowData = table.checkStatus('inventoryInfoTable');
			var data = rowData.data;
			var str = "";
			if(data.length == 0){
				toastr.warning("请至少选择一条记录！");
			}else{
				for(var i=0;i<data.length;i++){
            		str += data[i].id;
            		if(i != data.length-1){
            			str += ",";
            		}
            	}
				$.ajax({
			    	type:'post',
			    	url:'${pageContext.request.contextPath }/cancellingStockDetailManager/saveCancellingStockDetail.do',
			    	data:{"ids":str, "cancellingNumber":cancellingNumber, "source":source, "warehouseId":warehouseId, "customerId":customerId},
			    	dataType : "json",
			    	success:function(data){
			    		if(data > 0){
			    			toastr.success("新增成功！");
			    			setTimeout(function(){  
			    				//使用  setTimeout（）方法设定定时2000毫秒
								//关闭模态框
								//父页面刷新
								window.location.reload();  
							},1000);
			    		}else{
			    			toastr.warning("记录已存在，不能重复添加！");
			    		}
			    	}
			    })
			    layer.closeAll();
			}
		});
		
		//"退库单详情"的行内编辑事件
        table.on('edit(cancellingStockTableDetail)', function(obj){
            var fieldValue = obj.value, 	//得到修改后的值
                rowData = obj.data, 		//得到所在行所有键值
                fieldName = obj.field; 		//得到字段
            	//console.log(rowData.mNum);
           	var firstValue = $(this).prev().text(); 	//得到修改前的值
           	//alert("修改前：" + firstValue+ "，修改后：" + fieldValue);
            var patrn = /^[0-9]*$/;
            if(!patrn.test(fieldValue)){
            	toastr.warning("只能是数字！");
            	$(this)[0].value = $(this).prev().text(); //还原值
            	setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
					//关闭模态框
					// 父页面刷新
					window.location.reload();  
				},1000);
            } else {
            	/* if(fieldValue > firstValue){
            		toastr.warning("不能大于当前的库存！");
            		$(this)[0].value = $(this).prev().text();
            		setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
						//关闭模态框
						// 父页面刷新
						window.location.reload();  
					},1000);
            	}else{
            		layui.use('jquery',function(){
                        var $=layui.$;
                        $.ajax({
                            type: "post",
                            url: "${pageContext.request.contextPath }/cancellingStockDetailManager/updateCancellingStockDetail2.do",
                            data: { id:rowData.id, fieldName:fieldName, fieldValue:fieldValue },
                            success: function(data){
                                if(data > 0) {
                                	toastr.success("修改成功！");
                                } else {
                                	toastr.error("修改失败！");
                                }
                            }
                        });
                    });
            	} */
            	layui.use('jquery',function(){
                    var $=layui.$;
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath }/cancellingStockDetailManager/updateCancellingStockDetail2.do",
                        data: { id:rowData.id, fieldName:fieldName, fieldValue:fieldValue },
                        success: function(data){
                            if(data > 0){
                            	toastr.success("修改成功！");
                            }else{
                            	toastr.error("修改失败！");
                            }
                        }
                    });
                });
            }
        });
		
      	//批量删除退货单详情
		$('#delsDetail').click(function(obj){
        	var rowData = table.checkStatus('cancellingStockTableDetail');
			var data = rowData.data;
        	var str = "";
        	if(data.length==0){
        		toastr.warning("请至少选择一条记录！");
        	}else{
        		for(var i=0;i<data.length;i++){
            		str += data[i].id;
            		if(i != data.length-1){
            			str += ",";
            		}
            	}
        		layer.confirm('确定删除吗？', function(index){
    				$.ajax({
    			    	type:'post',
    			    	url:'${pageContext.request.contextPath }/cancellingStockDetailManager/deleteCancellingStockDetail.do',
    			    	data:{"ids":str},
    			    	dataType : "json",
    			    	success:function(data){
    			    		if(data>0){
    			    			toastr.success("删除成功！");
    			    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
    								//关闭模态框
    								// 父页面刷新
    								window.location.reload();  
    							},1000);
    			    		}else{
    			    			toastr.error("删除失败！");
    			    		}
    			    	}
    			    })
    		    layer.close(index);
    			});
        	}
		});
		
		/**
	     * 退库表单校验
	     */
	    form.verify({
			cancellingNumber: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '退库单号不能为空';
	    		}
	    	},
	    	createDate: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '创建时间不能为空';
	    		}
	    	},
	    	cancellingReason: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '退库原因不能为空';
	    		}
	    	},
	    	warehouseId: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '仓库名称不能为空';
	    		}
	    	},
	    	clientId: function(value){
	    		 var str = value.replace(/\s+/g,"");
	    		 if(str == ''){
	    			return '供应商名称不能为空';
	    		}
	    	},
	    });
	})	
</script>	

<script type="text/javascript">
	//生成退货单号
	function curentTimeNumber() {
		var now=new Date();
		var year = now.getFullYear();       //年
	    var month = now.getMonth() + 1;     //月
	    var day = now.getDate();            //日
	 	var hours = now.getHours(); //获取当前小时数(0-23)
   	var minutes = now.getMinutes(); //获取当前分钟数(0-59)
   	var seconds = now.getSeconds(); //获取当前秒数(0-59)
	    //var mill=now.getMilliseconds();
	    var time=year+""+add0(month)+""+add0(day)+""+add0(hours)+""+add0(minutes)+""+add0(seconds);
		return time;
	}

	//获取当前时间
	function curentTime() {
		var now=new Date();
		var year = now.getFullYear();       //年
	    var month = now.getMonth() + 1;     //月
	    var day = now.getDate();            //日
	    var time=year+"-"+add0(month)+"-"+add0(day);
		return time;
	}
	function add0(m){return m<10?'0'+m:m }
	toastrStyle()
	function selectWare(id){
		$("#warehouseId").find("option").not(":first").remove();
    	if(id == 1){
        	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getAllWarehouse.do",
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                	console.log(datas)
                	//设置下拉列表中的值的属性
                    for ( var i = 0; i < datas.length; i++) {
                    	//增加下拉列表。
                      	$("#warehouseId").append("<option value='"+datas[i].id+"'>"+datas[i].warehouse_name+"</option>");
                    }
                }
          	});
        }else{
        	$.ajax({
                type: "post",
                url: "${pageContext.request.contextPath }/cancellingStockManager/getAllBadnessWarehouse.do",
                dataType: 'JSON',
                async: false,
                success: function (datas) {
                	//设置下拉列表中的值的属性
                    for ( var i = 0; i < datas.length; i++) {
                    	//增加下拉列表。
                      	$("#warehouseId").append("<option value='"+datas[i].id+"'>"+datas[i].warehouse_name+"</option>");
        			}
                }
          	});
        }
    }
</script>

</body>
</html>